package cn.jett.domain.strategy.service.rule.chain.impl;


import cn.jett.domain.strategy.repository.IStrategyRepository;
import cn.jett.domain.strategy.service.armory.IStrategyDispatch;
import cn.jett.domain.strategy.service.rule.chain.AbstractLogicChain;

import cn.jett.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.jett.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author 战斗天使
 * @Description 权重方法
 * @Date 2024/6/19
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    protected IStrategyDispatch strategyDispatch;

    //用户积分
    private Long userScore;

    /**
     * 权重过滤方法
     * @param userId
     * @param strategyId
     * @return
     */
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());

        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());

        // 1. 解析权重规则值 4000:102,103,104,105 拆解为；4000 -> 4000:102,103,104,105 便于比对判断
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);
        if (null == analyticalValueGroup || analyticalValueGroup.isEmpty()) {
            log.warn("抽奖责任链-权重告警【策略配置权重，但ruleValue未配置相应值】 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
            return next().logic(userId, strategyId);
        }

        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticalSortedKeys);

        Long nextValue = analyticalSortedKeys.stream()
                .filter(key -> userScore >=key)
                .max(Comparator.naturalOrder())
                .orElse(null);


        if (null != nextValue){
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }

        // 6. 过滤其他责任链
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    /**
     * 解析权重
     * @param ruleValue
     * @return
     */
    public Map<Long,String> getAnalyticalValue(String ruleValue){
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        HashMap<Long, String> ruleValueMap = new HashMap<>();
        for(String ruleValueGroup:ruleValueGroups) {
            //判断当前组是否为空
            if (null == ruleValueGroup || ruleValueGroup.isEmpty()){
                return ruleValueMap;
            }
            String[] groupSplit = ruleValueGroup.split(Constants.COLON);
            //判断组的格式是否合法
            if (groupSplit.length != 2){
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            }
            ruleValueMap.put(Long.parseLong(groupSplit[0]),ruleValueGroup);
        }
        return ruleValueMap;
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }
}
